<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>日记管理</title>
    <!--<base th:href="${#request.getContextPath()}+'/'">-->
    <base th:href="@{/}">
    <!--bootstrap.min.css-->
    <link rel="stylesheet" th:href="@{/bootstrap/css/bootstrap.min.css}">
    <script th:src="@{/bootstrap/js/jquery.js}"></script>
    <script th:src="@{/bootstrap/js/bootstrap.min.js}"></script>
    <script th:src="@{/bootstrap/js/extendPagination.js}"></script>
    <script th:src="@{/bootstrap/js/layopen.js}"></script>
    <link rel="stylesheet" th:href="@{/bootstrap/font-awesome/css/font-awesome.min.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/bootstrap/css/my-layer-div.css}"/>
    <link rel="stylesheet" th:href="@{/bootstrap/sys/css/bootstrap_table_render.css}">
</head>
<body>
<div id="callBackPagination" class="piece">
    <div id="toolbar">
        <span class="tool_left">
            <span class="btn addBtn">添加</span>
        </span>
        <span class="tool_right"></span>
    </div>
    <div id="mainContent" style="overflow-y: auto;"></div>
    <div id="callBackPager"></div>
</div>
</body>
<script th:src="@{/bootstrap/js/JSONUtil.js}"></script>
<script th:src="@{/layer/layer.js}"></script>
<script th:src="@{/bootstrap/js/AjaxUtil.js}"></script>
<script type="text/javascript">
    // 初始化参数
    var CACHE = [];
    let totalCount = 252, showCount = 1, limit = 10;

    /**
     * 分页回调
     */
    loadInitTable(showCount, limit);

    /**
     * 建表(初始化数据)
     * @param data
     */
    function createTable(data) {
        let html = [];
        html.push(' <table class="table table-hover piece" style="margin-left: 0;">');
        // html.push(' <caption style="text-align: center;">您管理的日记</caption>');
        html.push('<thead><tr><th>名称</th><th>父节点</th><th>icon</th><th>创建时间</th><th>操作</th></tr></thead><tbody>');
        if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
                html.push('<tr><td>' + data[i].name + '</td>');
                let pH = createParent(data[i].parentNode);
                html.push('<td>' + pH + '</td>');
                html.push('<td>' + data[i].icon + '</td>');
                html.push('<td>' + JSONUtil.dateFormat('YYYY-mm-dd HH:MM:SS', new Date(data[i].createTime)) + '</td>');
                html.push('<td>' + createToolbar(data[i]) + '</td>');
                html.push('</tr>');
                data[i]['dataIndex'] = i;
            }
        }
        html.push('</tbody></table>');
        var mainObj = $('#mainContent');
        mainObj.empty();
        mainObj.html(html.join(''));
    }

    /**
     * 工具栏
     */
    function createToolbar(data) {
        return '<span onclick="editArchive(' + data.archiveKey + ')" class="tool_btn">编辑</span>' +
            '<span onclick="delArchive(' + data.archiveKey + ')" class="tool_btn">删除</span>';
    }

    /**
     * 编辑
     */
    function editArchive(key) {
        let row = getRowByKey(key);
        console.log(row);
        if (row !== null) {
            let json = {title: "编辑归档", area: 11, opt: 'edit', url: 'sys/edit_archive'};
            layopen(json, "init", row);
        }
    }

    /**
     * 添加按钮
     */
    $('.addBtn').on('click', function () {
        let json = {title: "新增归档", area: 11, url: 'sys/edit_archive'};
        layopen(json, "init", {});
    });

    /**
     * 成功回调
     */
    function editSuccessCallback(data) {
        let row = getRowByKey(data.archiveKey);
        updateRow(row, data);
        SuccessAlert('操作成功');
    }

    /**
     * 删除文章
     */
    function delArchive(key) {
        layer.confirm('您是是否需要删除此记录？', {
            btn: ['确定', '取消'] //按钮
        }, function () {
            let row = getRowByKey(key);
            let url = 'archive/delArchive';
            ajaxSyncPost(url, {archiveKey: row.archiveKey}, function () {
                layer.load(1);
            }, function (result) {
                layer.closeAll("loading");
                if (result.code === 200) {
                    let dataIndex = row['dataIndex'];
                    removeCacheByKey(dataIndex);
                    $("#mainContent .table tbody tr").eq(dataIndex).remove();
                    SuccessAlert('删除成功');
                } else {
                    WarnAlert('请求数据失败, 请稍后重试');
                }
            }, function () {
                layer.closeAll("loading");
                ErrorAlert('后台请求出错, 请稍后重试');
            });
        }, function () {

        });
    }


    /**
     * 创建标签Dom
     */
    function createParent(data) {
        if (data) {
            return '<span class="little_tag" data-id="' + data.archiveKey + '">' +
                '<i class="mgr5 fa fa-fw fa-code-fork"></i>' + data.name + '</span>';
        }
        return '<span class="little_tag">无</span>';
    }

    /**
     * 加载表格
     * @param curr
     * @param limit
     * @param totalCount
     */
    function loadTable(curr, limit, totalCount) {
        let url = 'archive/pageGetArchive';
        applyForPage(url, {pageIndex: curr, pageSize: limit}, function (result, count) {
            totalCount = count;
            CACHE = result;
            createTable(result);
        }, function (msg, code) {
            console.log('错误码: ' + code);
            WarnAlert(msg);
        });
    }

    /**
     * 初始化加载表格
     * @param curr
     * @param limit
     */
    function loadInitTable(curr, limit) {
        let url = 'archive/pageGetArchive';
        ajaxSyncPost(url, {pageIndex: curr, pageSize: limit}, function () {
            layer.load(1);
        }, function (result) {
            layer.closeAll("loading");
            if (result.code === 200) {
                let data = result.data;
                CACHE = data;
                totalCount = result.count;
                createTable(data);
                $('#callBackPager').extendPagination({
                    totalCount: totalCount,
                    showCount: showCount,
                    limit: limit,
                    callback: function (curr, limit, totalCount) {
                        loadTable(curr, limit, totalCount);
                    }
                });
            } else {
                WarnAlert('请求数据失败, 请稍后重试');
            }
        }, function () {
            layer.closeAll("loading");
            ErrorAlert('后台请求出错, 请稍后重试');
        });
    }

    /**
     * 获取当行数据
     * @param key
     * @returns {*}
     */
    function getRowByKey(key) {
        for (let i = 0; i < CACHE.length; i++) {
            let v = CACHE[i];
            if ((v.archiveKey + '') === (key + '')) {
                return v;
            }
        }
        return null;
    }

    /**
     * 更新行数据
     */
    function updateRow(row, data) {
        if (row) {
            let index = row['dataIndex'];
            updateRowCache(index, data);
            updateRowDom(index, data);
        } else {
            data['dataIndex'] = CACHE.length;
            CACHE.push(data);
            addRowDom(CACHE.length, data);
        }
    }

    /**
     * 更新行Dom
     */
    function updateRowDom(dataIndex, data) {
        let $tr = $("#mainContent .table tbody tr").eq(dataIndex);
        if ($tr) {
            $tr.find("td").eq(0).text(data.name);
            $tr.find("td").eq(1).text(data.icon);
            let tags = createParent(data.parentNode);
            $tr.find("td").eq(2).html(tags);
            $tr.find("td").eq(3).text(data.createTime);
            let opt = createToolbar(data);
            $tr.find("td").eq(4).html(opt);
        }
    }

    /**
     * 添加行Dom
     */
    function addRowDom(dataIndex, data) {
        let html = [];
        html.push('<tr><td>' + data.name + '</td>');
        let pH = createParent(data.parentNode);
        html.push('<td>' + pH + '</td>');
        html.push('<td>' + data.icon + '</td>');
        html.push('<td>' + JSONUtil.dateFormat('YYYY-mm-dd HH:MM:SS', new Date(data.createTime)) + '</td>');
        html.push('<td>' + createToolbar(data) + '</td>');
        html.push('</tr>');
        $("#mainContent .table tbody").append(html.join(''));
    }

    /**
     * 获取数据在缓存中的索引并替换他
     * @param dataIndex
     * @param data
     * @returns {null}
     */
    function updateRowCache(dataIndex, data) {
        data['dataIndex'] = dataIndex;
        removeCacheByKey(dataIndex);
        CACHE.push(data);
    }

    /**
     * 通过ID删除缓存数据
     * @param dataIndex
     */
    function removeCacheByKey(dataIndex) {
        for (let i = 0; i < CACHE.length; i++) {
            let v = CACHE[i];
            if (v.dataIndex === dataIndex) {
                CACHE.splice(i, 1);
                break;
            }
        }
        // 移动数据行索引
        for (let i = 0; i < CACHE.length; i++) {
            let v = CACHE[i];
            if (v.dataIndex > dataIndex) {
                let source = v.dataIndex;
                v['dataIndex'] = source - 1;
            }
        }
    }

</script>
</html>